import Taro from '@tarojs/taro'
import {SERVICE_URI} from '@/config.js'


export function validatePhone(phone) {
  return /^1(3|4|5|7|8|9)\d{9}$/.test(phone)
}

export async function  request({url, method, data, header, flag, isAuth}) {
  if(!flag) {
    // Taro.showLoading({mask: true})
  }
  let userInfo
  try {
    const value = await Taro.getStorage({key: 'userInfo'})
    userInfo = JSON.parse(value.data)
  } catch (e){
    userInfo = {}
  }
  const { token } = userInfo
  const res = await Taro.request({
    url: `${SERVICE_URI}${url}`,
    method: method || 'GET',
    data,
    header: {
      "Content-Type": "multipart/form-data",
      "token": token,
      ...header,
    },
  })
  if(!flag) {
    Taro.hideLoading()
  }
  if(flag) {
    const { data: { data: { payInfoVo }}} = res
    if(payInfoVo.status == 1) {
      return { error: true, num: payInfoVo.num, totalPrice: payInfoVo.totalPrice}
    } else {
      return {error: false}
    }
  }
  if(res.data.status != 0 ) {
    if(!isAuth) {
      Taro.showToast({
        title:  res.data.message,
        icon: 'none',
        mask: true
      })
    }
    // Taro.atMessage({  message: res.data.message, type: 'error' })
    // 登录过期处理，跳转登录页面
    if(res.data.status == -8 && !isAuth) {
      Taro.redirectTo({url: '/pages/authorize/index'})
    }
    return {error: true}
  }
  return {...res.data.data,error: false}
}

export function formatDate(fmt, time) { 
  const now = new Date(time)
  var o = {
      "M+": now.getMonth() + 1, //月份 
      "D+": now.getDate(), //日 
      "h+": now.getHours(), //小时 
      "m+": now.getMinutes(), //分 
      "s+": now.getSeconds(), //秒 
      "q+": Math.floor((now.getMonth() + 3) / 3), //季度 
      "S": now.getMilliseconds() //毫秒 
  };
  if (/(Y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (now.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
  if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}